<script setup lang="ts">
import { Ref, computed, onMounted, ref, toValue, unref } from 'vue'
import { CirclePlus } from '@element-plus/icons-vue';
import { EditPen } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import {
  reqfindAllAccountList,
  reqFindAccountById,
  reqUpdateOwnInfo,
  reqAddAccount
} from '@/api/userFaimily';
import { addAccountParams, resAccountListItem } from './type';
import { findCurrentUser } from '@/api';

onMounted(() => {
  findData()
})

// 搜索栏
const pageNo: Ref<number> = ref(1)
const pageSize = ref(10)


// 表格
const handleSizeChange = (val: number) => {
  pageSize.value = val
  findData()
}

const handleCurrentChange = (val: number) => {
  pageNo.value = val
  findData()
}

const total: Ref<number> = ref(0)
const tableData: Ref<Partial<resAccountListItem[]>> = ref([])

const findData = async (id?: string) => {
  if (id) {
    await reqFindAccountById({
      id
    }).then((res: any) => {
      const { code, data, total: tableTotal = 1 } = res

      if (code === 200) {
        tableData.value = [data]
        total.value = tableTotal

      } else {
        ElMessage({
          message: '请求异常',
          type: 'warning'
        })
      }
    })
  } else {
    await reqfindAllAccountList({
      pageNo: toValue(pageNo),
      pageSize: toValue(pageSize),
    }).then((res: any) => {
      const { code, data, total: tableTotal } = res

      if (code === 200) {
        tableData.value = data
        total.value = tableTotal

      } else {
        ElMessage({
          message: '请求异常',
          type: 'warning'
        })
      }
    })
  }
}

// 添加航班信息资讯弹窗
let dialogHost = ref(false)
let dialogHostTitle = ref('添加账号')
const formLabelWidth = '100px'
const addHsotForm: Ref<addAccountParams> = ref({
  username: "",
  password: "",
  role: "owner",
  phone: "",
  email: ""
})

const resetDialogHostFrom = () => {
  addHsotForm.value = {
    username: "",
    password: "",
    role: "",
    phone: "",
    email: ""
  }
}

const addHostDialog = () => {
  resetDialogHostFrom()
  dialogHostTitle.value = '添加账号'
  dialogHost.value = true
}

const addHostSubmit = async () => {
  if (dialogHostTitle.value == '添加账号') {
    await reqAddAccount(unref(addHsotForm)).then((res: any) => {
      const { code } = res

      if (code === 200) {
        dialogHost.value = false
        findData()
        ElMessage({
          message: '新增账号成功',
          type: 'success'
        })

      } else {
        const message = res.msg || '请求异常'
        ElMessage({
          message: message,
          type: 'warning'
        })
      }
    })
  } else if (dialogHostTitle.value == '修改个人信息') {
    await reqUpdateOwnInfo(unref(addHsotForm)).then((res: any) => {
      if (res.code === 200) {
        dialogHost.value = false
        findData()
        ElMessage({
          message: '修改个人信息成功',
          type: 'success'
        })

      } else {
        const message = res.msg || '请求异常'
        ElMessage({
          message: message,
          type: 'warning'
        })
      }
    })
  }

}

const updateHostDialog = async () => {
  resetDialogHostFrom()
  dialogHostTitle.value = '修改个人信息'
  dialogHost.value = true
  await findCurrentUser().then((res: any) => {
    addHsotForm.value = res.data
    // addHsotForm.value.role = addHsotForm.value.role == 'admin' ? '0' : '1'
    console.log(addHsotForm, 'add', res.data);
  })
}
const findRoleInfo = async (id: string) => {
  resetDialogHostFrom()
  dialogHostTitle.value = '查看账号'
  dialogHost.value = true
  await reqFindAccountById({
    id
  }).then((res: any) => {
    const { code, data } = res

    if (code === 200) {
      addHsotForm.value = data
      addHsotForm.value.role = addHsotForm.value.role == 'admin' ? '0' : '1'
    } else {
      ElMessage({
        message: '请求异常',
        type: 'warning'
      })
    }
  })
}

const isReadonlyHandler = computed(() => {
  return dialogHostTitle.value !== '查看账号'
})

</script>

<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span><strong>角色管理</strong></span>
      </div>
    </template>
    <!-- <div class="query-input">
      <el-input v-model="searchFrom.id" placeholder="请输入用户id" />
      <el-button type="primary" @click="findData(searchFrom.id)">
        <el-icon>
          <Search />
        </el-icon>
        查询
      </el-button>
      <el-button type="danger" @click="reset()">
        <el-icon>
          <Refresh />
        </el-icon>
        重置
      </el-button>
    </div> -->

  </el-card>

  <el-card>
    <div>
      <el-button key="'添加账号'" @click="addHostDialog()" :icon="CirclePlus" type="primary" text bg
        class="addUser">添加账号</el-button>
      <el-button key="'修改个人账号信息'" @click="updateHostDialog()" :icon="EditPen" type="primary" text bg
        class="addUser">修改个人账号信息</el-button>
    </div>
    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="role" label="角色">
        <template #default="scope">
          <div>{{ scope.row.role == 'admin' ? '管理员' : '用户' }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="lastLoginTime" label="最后登录时间">
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-space wrap>
            <el-button type="primary" size="small" plain @click="findRoleInfo(scope.row.id)">查看</el-button>
          </el-space>
        </template>
      </el-table-column>
    </el-table>

    <div class="demo-pagination-block">
      <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
        :background="false" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </el-card>
  <!-- 添加户主弹框 -->
  <el-dialog v-model="dialogHost" :title="dialogHostTitle">
    <el-form :model="addHsotForm">
      <el-form-item label="用户名:" :label-width="formLabelWidth" clearable required>
        <el-input v-model="addHsotForm.username" autocomplete="off" placeholder="请输入用户名" :disabled="!isReadonlyHandler" />
      </el-form-item>
      <el-form-item label="密码:" v-if="dialogHostTitle !== '查看账号'" :label-width="formLabelWidth" clearable required>
        <el-input v-model="addHsotForm.password" type="password" placeholder="请输入密码" show-password
          :disabled="!isReadonlyHandler" />
      </el-form-item>
      <el-form-item v-if="dialogHostTitle == '添加账号'" label="角色:" :label-width="formLabelWidth" clearable required>
        <el-radio-group v-model="addHsotForm.role" :disabled="!isReadonlyHandler">
          <el-radio label="admin" size="large">管理员</el-radio>
          <el-radio label="owner" size="large">用户</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="手机号:" :label-width="formLabelWidth" clearable required>
        <el-input v-model="addHsotForm.phone" autocomplete="off" placeholder="请输入手机号" :disabled="!isReadonlyHandler" />
      </el-form-item>
      <el-form-item label="邮箱:" :label-width="formLabelWidth" clearable required>
        <el-input v-model="addHsotForm.email" autocomplete="off" placeholder="请输入邮箱" :disabled="!isReadonlyHandler" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogHost = false">取消</el-button>
        <el-button v-if="isReadonlyHandler" type="primary" @click="addHostSubmit()">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-input {
  margin-right: 5px;
  width: 400px;
}

.query-input {
  display: flex;
  gap: 10;
}

.el-card {
  margin-bottom: 10px;
}

.demo-pagination-block {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.addUser {
  float: right;
  margin-right: 10px;
}

.el-button--text {
  margin-right: 15px;
}

.el-select {
  width: 300px;
}

/* 
.el-input & .el-textarea  {
  width: 300px;
} */
.el-textarea {
  width: 400px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>